﻿(function () {
    "use strict";

    var WRCSObject = WindowsStoreWRC.WRCServiceCom;

    var searchDataAdapter = WinJS.Class.define(
        function (textoPesquisa, numPagina, porPagina) {
            this._textoPesquisa = textoPesquisa;
            this._numPagina = numPagina;
            this._porPagina = porPagina;
        },
        {
            itemFromIndex: function (requestIndex, countBefore, countAfter) {

                var that = this;

                var fetchSize, fetchIndex;
                // See which side of the requestIndex is the overlap
                if (countBefore > countAfter) {
                    //Limit the overlap
                    countAfter = Math.min(countAfter, 10);
                    //Bound the request size based on the minimum and maximum sizes
                    var fetchBefore = Math.max(Math.min(countBefore, that._maxPageSize - (countAfter + 1)), that._minPageSize - (countAfter + 1));
                    fetchSize = fetchBefore + countAfter + 1;
                    fetchIndex = requestIndex - fetchBefore;
                } else {
                    countBefore = Math.min(countBefore, 10);
                    var fetchAfter = Math.max(Math.min(countAfter, that._maxPageSize - (countBefore + 1)), that._minPageSize - (countBefore + 1));
                    fetchSize = countBefore + fetchAfter + 1;
                    fetchIndex = requestIndex - countBefore;
                }

                return WRCSObject.buscaProgramas(that._textoPesquisa, that._numPagina, that._porPagina).then(
                function complete(result) {
                    var JSONResult = JSON.parse(result);
                    return {
                        items: JSONResult,
                        offset: requestIndex - fetchIndex,
                        totalCount: JSONResult.length
                    }
                },
                function error(result) {

                },
                function progress() {

                });
            }
        }
    );

    WinJS.Namespace.define("WebServiceDataLayer", {
        datasource: WinJS.Class.derive(WinJS.UI.VirtualizedDataSource, function (textoPesquisa, numPagina, porPagina) {
            this._baseDataSourceConstructor(new searchDataAdapter(textoPesquisa, numPagina, porPagina));
        })
    });
})();